package com.xd.clap.utils;

import cn.hutool.core.text.StrFormatter;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.kevinsawicki.http.HttpRequest;
import com.xd.clap.commons.Const;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class LoginUtil {
    private static final String getAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token";
    private static final String getPhoneNumberUrl = "https://api.weixin.qq.com/wxa/business/getuserphonenumber";

    public static String getAccessToken() {
        String url = LoginUtil.getAccessTokenUrl + "?grant_type=client_credential&appid=" + Const.APPID + "&secret=" + Const.SECRET;
        String response = HttpRequest.get(url).body();
        JSONObject jsonObject = JSONObject.parseObject(response);
        return jsonObject.getString("access_token");
    }
    public static String getPhoneNumber(String code) {
        String accessToken = LoginUtil.getAccessToken();
        JSONObject data = new JSONObject();
        data.put("code", code);
        String url = LoginUtil.getPhoneNumberUrl + "?access_token=" + accessToken;
        String response = HttpRequest.post(url).acceptJson().send(data.toString()).body();
        JSONObject jsonObject = JSONObject.parseObject(response);
        if (jsonObject.getString("errcode").equals("0")) {
            jsonObject = JSONObject.parseObject(jsonObject.getString("phone_info"));
            return jsonObject.getString("phoneNumber");
        }
        return null;
    }


    public static String toWxLogin(String code){
        String getOpenIdUrl = "https://api.weixin.qq.com/sns/jscode2session?appid={}&secret={}&js_code={}&grant_type=authorization_code";
        //1.通过前端给的code获取openid和access_token还有unionid
        String getTokenOpenid = StrFormatter.format(getOpenIdUrl,Const.APPID, Const.SECRET, code);
        String data = HttpUtil.get(getTokenOpenid);
        log.info("微信获取获取openid和session_key,返回结果======{}=====",data);
        //json=>bean
        JSONObject jsonObject = JSONObject.parseObject(data);
        String openid = jsonObject.getString("openid");
        //获取用户信息失败 抛异常
        if (openid == null){
            return null;
        }
        return openid;
    }
}
